// API相关的composable
export const useApi = () => {
  const config = useRuntimeConfig();

  // 创建API客户端
  const apiClient = $fetch.create({
    baseURL: config.public.apiBase || "http://localhost:3001",
    headers: {
      "Content-Type": "application/json",
    },
    onRequest({ request, options }) {
      // 添加认证token
      const token = useCookie("auth_token");
      if (token.value) {
        options.headers = {
          ...options.headers,
          Authorization: `Bearer ${token.value}`,
        };
      }
    },
    onResponse({ response }) {
      // 处理通用错误
      if (response.status >= 400) {
        const data = response._data;
        if (data && data.message) {
          ElMessage.error(data.message);
        }
      }
    },
    onResponseError({ response }) {
      // 处理认证错误
      if (response?.status === 401) {
        const token = useCookie("auth_token");
        token.value = null;
        navigateTo("/login");
        ElMessage.error("登录已过期，请重新登录");
      } else if (response?.status >= 500) {
        ElMessage.error("服务器错误，请稍后重试");
      }
    },
  });

  // 返回API方法
  return {
    client: apiClient,
    get: (url: string, params?: any) =>
      apiClient(url, { method: "GET", params }),
    post: (url: string, body?: any) => apiClient(url, { method: "POST", body }),
    put: (url: string, body?: any) => apiClient(url, { method: "PUT", body }),
    delete: (url: string) => apiClient(url, { method: "DELETE" }),
    patch: (url: string, body?: any) =>
      apiClient(url, { method: "PATCH", body }),
  };
};
